//main.cpp
/********************************************************************************
*																				*
*	Author:			Jared Szechy												*
*	Assignment:		Assignment 1												*
*	Class:			CPS-151														*
*	Instructor:		V. Starkley													*
*	Due Date:		August 30													*
*																				*
*	This program simulates a vending machine.									*
*																				*
********************************************************************************/

#include <iostream>
#include <fstream>
#include <string>
#include "dispenser.h"
#include "cashRegister.h"
#include "functions.h"
#include "unsorted.h"
using namespace std;

main()
{
	//variable declarations
	string selection;
	Dispenser tempDisp;
	UnsortedType vendingMachine;
	CashRegister cash;
	ifstream fin;
	ofstream fout;

	//open input file
	fin.open("inventory.txt");
	if(fin.fail())
	{
		cout << "Error opening inventory.txt" << endl;
		exit(1);
	}

	//import inventory from file
	readItem(fin, vendingMachine);
	while(!fin.fail() && !vendingMachine.IsFull())
	{
		readItem(fin, vendingMachine);
	}
	fin.close();

	//display inventory	
	cout << fixed << showpoint;
	cout.precision(2);
	printInventory(cout, vendingMachine);

	//start sales loop
	while (true)
	{
		//prompt user to enter a item number
		cout << endl << "If you would like to make a purchase enter the product name as listed above," 
			 << endl << "else enter 00." << endl << endl << "Selection: ";
		while(isspace(cin.peek()))
			cin.ignore();
		getline(cin, selection);

		//if user selects 00 quit the loop
		if (selection == "00")
			break;
		else
		{
			//check if a valid selection was made
			tempDisp.setProductName(selection);
			if (!vendingMachine.RetrieveItem(tempDisp))
			{
				cout << endl << "Invalid product selection, please try again." << endl << endl;
				continue;
			}
			//check if there is sufficiant quantity of selection
			if (tempDisp.getQuantityOnHand() == 0)
			{
				cout << endl << "Sorry, selection is sold out. Please make a different selection."
					 << endl << endl;
				continue;
			}
			
			//get payment for the selected item
			tender(cout, tempDisp, cash, vendingMachine);
			
			//re display inventory
			printInventory(cout, vendingMachine);
		}
	}
    
	//open output stream
	fout.open("inventory.txt");
	if(fout.fail())
	{
		cout << "Could not open inventory.txt" << endl;
		exit(1);
	}

	//write inventory back to file
	writeInventory(fout, vendingMachine);

	//if change remaining from transaction(s) display that it has been returned
	if(cash.getCashOnHand() > 0)
		cout << "Your extra change of $" << cash.getCashOnHand() << " has been return to you." << endl;
	cout << "THANK YOU!" << endl;

	
	system("pause");
	return 0;
}